import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import { CacheManager } from '@/cache'
import { useMenuStore } from '@/stores/menu'
import pinia from '@/stores'
import { MenuUtils } from '@/utils/MenuUtils'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'
import { useSystemStore } from '@/stores/system'

const menuStore = useMenuStore(pinia)
const systemStore = useSystemStore(pinia)

const staticMenus: Array<MenuRecordRaw> = [
  {
    title: '登录页面',
    menuType: 'router',
    path: '/loginPage',
    component: '/system/Login.vue',
    keepAlive: true,
    hidden: true,
    componentName: 'Login',
    sort: 1,
    isTopPage: true
  },
  {
    title: '没有权限',
    menuType: 'router',
    path: '/401',
    component: '/error/401.vue',
    keepAlive: false,
    hidden: true,
    sort: 2,
    isTopPage: true
  },
  {
    title: '找不到此页面',
    menuType: 'router',
    path: '/:pathMatch(.*)*',
    component: '/error/404.vue',
    keepAlive: false,
    hidden: true,
    sort: Number.MAX_VALUE,
    isTopPage: true
  }
]

// const menus: Array<MenuRecordRaw> = [
//   {
//     title: '首页',
//     menuType: 'router',
//     path: '/',
//     component: '/system/Home.vue',
//     keepAlive: true,
//     componentName: 'Home'
//   },
//   {
//     title: '菜单1',
//     menuType: 'dir',
//     icon: 'fold',
//     children: [{
//       title: '菜单1-1',
//       menuType: 'router',
//       path: '/path1-1',
//       component: '/system/System.vue',
//       keepAlive: true,
//       componentName: 'System',
//       icon: 'location'
//     },
//       {
//         title: '菜单1-2',
//         menuType: 'router',
//         path: '/path1-2',
//         component: '/system/About.vue',
//         keepAlive: true,
//         componentName: 'About',
//         icon: 'location',
//
//         children: [
//           {
//             title: '菜单1-2-1',
//             menuType: 'router',
//             path: '/path1-2-1',
//             component: '/system/System.vue',
//             keepAlive: true,
//             componentName: 'System',
//             icon: 'location'
//           },
//           {
//             title: '菜单1-2-2',
//             menuType: 'router',
//             path: '/path1-2-2',
//             component: '/system/About.vue',
//             keepAlive: true,
//             componentName: 'About',
//             icon: 'location'
//           }
//         ]
//       }]
//   },
//   {
//     title: '跳转外部链接',
//     menuType: 'link',
//     oriURL: 'https://www.baidu.com',
//     icon: 'location'
//   },
//   {
//     title: 'Iframe',
//     menuType: 'iframe',
//     oriURL: 'http://localhost:8080',
//     icon: 'location'
//   }
// ]

const menuMap = new Map<string, MenuRecordRaw>()
const routerSet = new Set<RouteRecordRaw>()
const keepAliveNameSet = new Set<string>()
MenuUtils.processList(staticMenus, menuMap, routerSet, keepAliveNameSet)
/**
 * 保存静态菜单
 */
menuStore.saveStaticMenus([...menuMap.values()])

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  // history: createWebHashHistory(),
  routes: [...menuStore.staticRouterSet]
})

export default router

/**
 * 允许匿名访问的路径
 */
const anonymousAccessPath = ['/loginPage']

router.beforeEach(async (to, from) => {
  if (!NProgress.isStarted()) {
    systemStore.openLoading()
  }
  NProgress.start()
  //当前访问路径实际匹配的路由路径
  const path = to.path
  if (CacheManager.getToken()) {
    if (!menuStore.loading) {
      await menuStore.initDynamicMenus()
      if (path === '/loginPage') {
        //token存在，不允许访问登录或注册页面
        return { path: '/' }
      } else {
        return { path: to.path, query: to.query }
      }
    } else {
      if (path === '/loginPage') {
        //token存在，不允许访问登录或注册页面
        return { path: '/' }
      }
    }
  } else {
    //token不存在，只能进入允许匿名访问的页面
    if (anonymousAccessPath.indexOf(path) !== -1) {
    } else {
      return { path: '/loginPage' }
    }
  }
})
router.afterEach(() => {
  menuStore.pushHistory()
  NProgress.done()
  if (!NProgress.isStarted()) {
    systemStore.closeLoading()
  }
})
